/*
 * 角色验证守卫，用于验证用户角色
 */

import type { CanActivate, ExecutionContext } from '@nestjs/common'
import type { Reflector } from '@nestjs/core'
import type { Request } from 'express'
import {

  HttpStatus,
  Injectable,
} from '@nestjs/common'
import { CustomExceptionFilter } from '@/common/filters'

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  // context 请求的(Response/Request)的引用
  canActivate(context: ExecutionContext): boolean {
    // 从元数据中获取角色信息
    const requiredRoles = this.reflector.get<string[]>(
      'roles',
      context.getHandler(),
    )

    // 如果没有设置角色要求,则允许访问
    if (requiredRoles?.length === 0) {
      return true
    }

    const request = context
      .switchToHttp()
      .getRequest<Request & { user: { role: string } }>()
    const user = request.user
    if (!user) {
      throw new CustomExceptionFilter(
        '用户角色不存在',
        HttpStatus.UNAUTHORIZED,
      )
    }

    const hasRole = requiredRoles.includes(user.role)
    return hasRole
  }
}
